package com.yunfeng.supercall.activity;

import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import u.aly.an;

import android.R.animator;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.SharePreferenceUtil;
import com.lin.utils.Utils;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.utils.JsonUtils;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.service.CallConnectionService;
import com.yunfeng.supercall.service.HandlePhoneDataIntentService;

public class LoginActivity extends BaseActivity {

	private EditText mEditTextPhone;
	private EditText mEditTextPwd;
	boolean isClickable = true;
	Session mSession;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		String action = getIntent().getAction();
		if(action != null && ACTION_FINSIH.equalsIgnoreCase(action)) {
			isClickable = false;
			mHandlerDelay.sendEmptyMessageDelayed(0, 3000);
		}

		SharedPreferences sp = getActivity().getSharedPreferences(
				"isInstructionLoaded", 3);
		//创建桌面快捷方式
		if(sp.getBoolean("isInstructionLoaded", false) == false) {
			if (!Utils.isMiu()) {
				//				Utils.createShortCut(getActivity(), R.drawable.ic_launcher, R.string.app_name);
				//				Utils.addShortCut(getActivity());
				Utils.addShortcut(this,"超号");
			}
		}

		Editor mEditor = sp.edit();
		mEditor.putBoolean("isInstructionLoaded", true);
		mEditor.commit();

		mEditTextPhone = (EditText) findViewById(R.id.et_code);
		mEditTextPwd = (EditText) findViewById(R.id.et_pass);

		String reason = checkReason();
		try {
			UserBean mUser = getUser(getActivity());
			if (mUser != null) {
				setTextViewText(R.id.et_code, mUser.getPhone());
				setTextViewText(R.id.et_pass, mUser.getPassword());
				if (getIntent().getBooleanExtra("autologin", true)
						&& TextUtils.isEmpty(reason)) {
					login(null);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(!TextUtils.isEmpty(SharePreferenceUtil.getInstance().getUserName(getApplicationContext()))) {
			setTextViewText(R.id.et_code, SharePreferenceUtil.getInstance().getUserName(getApplicationContext()));
			setTextViewText(R.id.et_pass, SharePreferenceUtil.getInstance().getPassword(getApplicationContext()));
			//			login();
		}
	}

	Handler mHandlerDelay = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			isClickable = true;
		}
	};
	/**
	 * 
	 * @return
	 */
	private String checkReason() {
		String reason = getIntent().getStringExtra("reason");
		if (!TextUtils.isEmpty(reason)) {
			Builder mBuilder = new Builder(this);
			mBuilder.setMessage(reason);
			mBuilder.setNegativeButton(android.R.string.ok, null);
			mBuilder.setTitle(R.string.notice);
			mBuilder.show();
			JPushInterface.setAlias(getApplicationContext(), "",
					new TagAliasCallback() {

				@Override
				public void gotResult(int arg0, String arg1,
						Set<String> arg2) {
					// TODO Auto-generated method stub

				}
			});
		}
		return reason;
	}

	/**
	 * 更改密码
	 * 
	 * @param v
	 */
	public void changePass(View v) {
		startActivity(new Intent(this, ResetPasswordStep1Activity.class));
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
		String reason = getIntent().getStringExtra("reason");
		if (!TextUtils.isEmpty(reason)) {
			Builder mBuilder = new Builder(this);
			mBuilder.setMessage(reason);
			mBuilder.setNegativeButton(android.R.string.ok, null);
			mBuilder.setTitle(R.string.notice);
			mBuilder.show();
		}
	}

	public void reg(View v) {
		startActivity(new Intent(this, ChooseRegModeActivity.class));
	}

	public void login(View v) {
		login();
	}


	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			//			Parameters.mArrayListPhoneContactsBean =  Utils.getPeopleInPhone2(getApplicationContext());
			mHandler.sendEmptyMessage(0);
		}

	};

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			String phone = getTextViewText(R.id.et_code);
			final String pass = getTextViewText(R.id.et_pass);
			if (TextUtils.isEmpty(phone)) {
				showToast(R.string.input_phone_or_super_number);
				return;
			}
			// if (phone != null) {
			// if (phone.length() == 11 && !BaseAppContext.isMobileNO(phone)) {
			// showToast("请输入有效的手机号码");
			// return;
			// }
			// }
			if (TextUtils.isEmpty(pass)) {
				showToast(R.string.input_pass);
				return;
			}
			JSONObject json = getBaseParams(getActivity());
			try {
				json.put(KEY_PHONE, phone);
				json.put(KEY_PASS, pass);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			mSession.getUserLogin2(getApplicationContext(), phone, pass, new ResultReceiver<String>(){

				@Override
				public void onResult(boolean last, String data) {
					// TODO Auto-generated method stub
					if(data != null) { //有网络情况下
						startService(new Intent(LoginActivity.this, HandlePhoneDataIntentService.class));
						SharePreferenceUtil.getInstance().updateUserInfo(LoginActivity.this, mEditTextPhone.getText().toString(), mEditTextPwd.getText().toString());
						cancelProgressDialog();

						SharePreferenceUtil.getInstance().saveUserInfo(getApplicationContext(), data);
						UserBean mUser = JsonUtils.parse(
								data.substring(1, data.length() - 1), UserBean.class);
						mUser.setPassword(pass);
						getLoginManager(getActivity()).saveUser(mUser);
						startService(new Intent(LoginActivity.this,
								CallConnectionService.class).putExtra("code",
										mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
						// startActivity(new Intent(LoginActivity.this,
						// MainActivity.class));
						if (getIntent().getBooleanExtra(KEY_DATA, true)) {
							showToast(R.string.login_success);
							startActivity(new Intent(LoginActivity.this,
									MainActivity.class));

							finish();
							ManagerFactory.clearAll();
						} else {
							setResult(RESULT_OK, new Intent().putExtra(KEY_DATA, true));
							finish();
						}
					} else {
						cancelProgressDialog();
						String result = SharePreferenceUtil.getInstance().getUserInfo(getApplicationContext());
						if(!TextUtils.isEmpty(result)) {
							UserBean mUser = JsonUtils.parse(
									result.substring(1, result.length() - 1), UserBean.class);
							mUser.setPassword(pass);
							getLoginManager(getActivity()).saveUser(mUser);
							startService(new Intent(LoginActivity.this,
									CallConnectionService.class).putExtra("code",
											mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
							// startActivity(new Intent(LoginActivity.this,
							// MainActivity.class));
							if (getIntent().getBooleanExtra(KEY_DATA, true)) {
								showToast(R.string.login_success);
								startService(new Intent(LoginActivity.this, HandlePhoneDataIntentService.class));
								startActivity(new Intent(LoginActivity.this,
										MainActivity.class));

								finish();
								ManagerFactory.clearAll();
							}	
						} else {
							showToast("请确保网络并输入正确账号密码");	
						}
					}
				}

			});

		/*	mHttpClient.post(Constants.FUNCTION_LOGIN, json, new MyAjaxCallBack() {

				@Override
				public void onReceiveError(String msg, String errorCode) {
					// TODO Auto-generated method stub

					cancelProgressDialog();
					String result = SharePreferenceUtil.getInstance().getUserInfo(getApplicationContext());
					if(!TextUtils.isEmpty(result)) {
						UserBean mUser = JsonUtils.parse(
								result.substring(1, result.length() - 1), UserBean.class);
						mUser.setPassword(pass);
						getLoginManager(getActivity()).saveUser(mUser);
						startService(new Intent(LoginActivity.this,
								CallConnectionService.class).putExtra("code",
										mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
						// startActivity(new Intent(LoginActivity.this,
						// MainActivity.class));
						if (getIntent().getBooleanExtra(KEY_DATA, true)) {
							showToast(R.string.login_success);
							startService(new Intent(LoginActivity.this, HandlePhoneDataIntentService.class));
							startActivity(new Intent(LoginActivity.this,
									MainActivity.class));

							finish();
							ManagerFactory.clearAll();
						}	
					} else {
						showToast("请确保网络并输入正确账号密码");	
					}
				}

				@Override
				public void onReceiveData(String data, String msg) {
					// TODO Auto-generated method stub

					startService(new Intent(LoginActivity.this, HandlePhoneDataIntentService.class));
					SharePreferenceUtil.getInstance().updateUserInfo(LoginActivity.this, mEditTextPhone.getText().toString(), mEditTextPwd.getText().toString());
					cancelProgressDialog();

					SharePreferenceUtil.getInstance().saveUserInfo(getApplicationContext(), data);
					UserBean mUser = JsonUtils.parse(
							data.substring(1, data.length() - 1), UserBean.class);
					mUser.setPassword(pass);
					getLoginManager(getActivity()).saveUser(mUser);
					startService(new Intent(LoginActivity.this,
							CallConnectionService.class).putExtra("code",
									mUser.getVo_id()).putExtra("pass", mUser.getVo_pass()));
					// startActivity(new Intent(LoginActivity.this,
					// MainActivity.class));
					if (getIntent().getBooleanExtra(KEY_DATA, true)) {
						showToast(R.string.login_success);
						startActivity(new Intent(LoginActivity.this,
								MainActivity.class));

						finish();
						ManagerFactory.clearAll();
					} else {
						setResult(RESULT_OK, new Intent().putExtra(KEY_DATA, true));
						finish();
					}
				}
			});*/
		}

	};

	private void login() {
		if(isClickable == false)	return;
		new Thread(runnable).start();


		showProgressDialog(R.string.logining);

	}

}
